
// $(function (){


//获取token
    var token = CoreUtil.getData("access_token");
//地址栏转义token中的#号
    var tokenQuery = token.replace("#", "%23");
    var tableIns1;
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var $ = jQuery = layui.jquery;
    var laydate = layui.laydate;
    info();
    layui.use(['table', 'layer', 'laydate'], function () {
        //表头工具
        table.on('toolbar(showTable)', function(obj){
            switch(obj.event){
                case 'batchDeleted':
                    var checkStatus = table.checkStatus(obj.config.id);
                    var data = checkStatus.data;
                    if(data.length==0){
                        layer.msg("请选择要批量删除的列");
                    }else {
                        var ids = [];
                        $(data).each(function (index,item) {
                            ids.push(item.id);
                        });
                        tipDialog(ids);
                    }
                    break;
                case 'addTypezjl':
                    $(".table_div").hide();
                    $(".tcType2").hide();
                    $("#fromgly").hide();
                    $(".operation").show();
                    $(".title").html("新增坐席");
                    $(".operation input[name=id]").val("");
                    $(".operation input[name=accountid]").val("");
                    $(".operation input[name=password]").val("");
                    $(".operation input[name=corporatename]").val("");
                    $(".operation input[name=contacts]").val("");
                    $(".operation input[name=phone]").val("");
                    $(".operation select[name=roleId]").val("");
                    $(".operation input[name=state]").val("");
                    $(".operation input[name=tcType1]").val("");
                    $(".operation input[name=tcType2]").val("");
                    $(".operation input[name=residue1]").val("");
                    $(".operation input[name=residue2]").val("");
                    $(".operation input[name=amount]").val("");
                    $(".operation input[name=createtime]").val("");
                    $(".operation input[name=endtime]").val("");
                    $(".operation input[name=tccztime]").val("");
                    $(".operation input[name=line]").val("");
                    $(".operation input[name=apkid]").val("");
                    $(".operation input[name=ak]").val("");
                    $(".operation input[name=sk]").val("");
                    $(".operation input[name=seats]").val("");
                    $(".operation input[name=mode]").val("");
                    $(".operation input[name=salesname]").val("");
                    $(".operation input[name=xiaohao]").val("");
                    break;
                case 'addType1':
                    $(".table_div").hide();
                    $(".tcType2").hide();
                    $("#fromzjl").hide();
                    $(".operation").show();
                    $(".title").html("新增坐席");
                    $(".operation input[name=id]").val("");
                    $(".operation input[name=accountid]").val("");
                    $(".operation input[name=password]").val("");
                    $(".operation input[name=corporatename]").val("");
                    $(".operation input[name=contacts]").val("");
                    $(".operation input[name=phone]").val("");
                    $(".operation select[name=roleId]").val("");
                    $(".operation input[name=state]").val("");
                    $(".operation input[name=tcType1]").val("");
                    $(".operation input[name=tcType2]").val("");
                    $(".operation input[name=residue1]").val("");
                    $(".operation input[name=residue2]").val("");
                    $(".operation input[name=amount]").val("");
                    $(".operation input[name=createtime]").val("");
                    $(".operation input[name=endtime]").val("");
                    $(".operation input[name=tccztime]").val("");
                    $(".operation input[name=line]").val("");
                    $(".operation input[name=apkid]").val("");
                    $(".operation input[name=ak]").val("");
                    $(".operation input[name=sk]").val("");
                    $(".operation input[name=seats]").val("");
                    $(".operation input[name=mode]").val("");
                    $(".operation input[name=salesname]").val("");
                    $(".operation input[name=xiaohao]").val("");
                    break;
                case 'addType2':
                    $(".table_div").hide();
                    $("#fromzjl").hide();
                    $(".tcType1").hide();//套餐模式
                    $(".operation").show();
                    $(".title").html("新增坐席(套餐模式)");
                    $(".operation input[name=id]").val("");
                    $(".operation input[name=accountid]").val("");
                    $(".operation input[name=corporatename]").val("");
                    $(".operation input[name=contacts]").val("");
                    $(".operation input[name=phone]").val("");
                    $(".operation select[name=roleId]").val("");
                    $(".operation input[name=state]").val("");
                    $(".operation input[name=tcType1]").val("");
                    $(".operation input[name=tcType2]").val("");
                    $(".operation input[name=residue1]").val("");
                    $(".operation input[name=residue2]").val("");
                    $(".operation input[name=amount]").val("");
                    $(".operation input[name=createtime]").val("");
                    $(".operation input[name=endtime]").val("");
                    $(".operation input[name=tccztime]").val("");
                    $(".operation input[name=line]").val("");
                    $(".operation input[name=apkid]").val("");
                    $(".operation input[name=ak]").val("");
                    $(".operation input[name=sk]").val("");
                    $(".operation input[name=seats]").val("");
                    $(".operation input[name=mode]").val("");
                    $(".operation input[name=salesname]").val("");
                    $(".operation input[name=xiaohao]").val("");
                    break;
            };
        });
        //列操作
        table.on('tool(showTable)',function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'del':
                    var ids=[];
                    ids.push(data.id);
                    tipDialog(ids);
                    break;
                case 'edit':
                    //给表单赋值
                    form.val("tSeatsInfo",{
                        id:data.id,
                        roleId:data.role,
                        accountid:data.accountid,
                        corporatename:data.corporatename,
                        contacts:data.contacts,
                        phone:data.phone,
                        state:data.state,
                        tcType:data.tcType,
                        residue:data.residue,
                        amount:data.amount,
                        endtime:data.endtime,
                        line:data.line,
                        seats:data.seats,
                        mode:data.mode,
                        salesname:data.salesname
                    })
                    $(".table_div").hide();
                    $("#fromzjl").hide();
                    $(".operation").show();
                    $(".title").html("编辑");
                    break;
                case 'editzjl':
                    //给表单赋值
                    form.val("tSeatsInfo",{
                        id:data.id,
                        roleId:data.role,
                        accountid:data.accountid,
                        corporatename:data.corporatename,
                        contacts:data.contacts,
                        phone:data.phone,
                        state:data.state,
                        tcType:data.tcType,
                        residue:data.residue,
                        amount:data.amount,
                        endtime:data.endtime,
                        line:data.line,
                        seats:data.seats,
                        mode:data.mode,
                        salesname:data.salesname,
                        dept:data.dept
                    })
                    $(".table_div").hide();
                    $("#fromgly").hide();
                    $(".operation").show();
                    $(".title").html("编辑");
                    break;
                case 'editfzs':
                    //给表单赋值
                    form.val("editfzsInfo",{
                        id:data.id,
                        mobile:data.phone,
                    })
                    layer.open({
                        type: 1,
                        offset: '50px',
                        skin: 'layui-layer-molv',
                        title: "编辑分钟数",
                        area: ['800px', '400px'],
                        shade: 0,
                        shadeClose: false,
                        content: jQuery("#editfzs"),
                        btn: ['确定', '取消'],
                        yes: function (index) {
                            var id = $.trim($("#id").val());//Id
                            var fzs = $.trim($("#fzs").val());//分钟数
                            var mobile = $("#mobile").val();//手机号
                            var smscode = $("#smscode").val();//验证码
                            var cztype = $("#cztype").val();//操作类型
                            var params = {
                                id: id,
                                fzs: fzs,
                                mobile: mobile,
                                smscode: smscode,
                                cztype: cztype
                            }
                            CoreUtil.sendPut("/tSeats/updateFzs", params, function (res) {
                                var code = res.code;
                                //同步数据失败
                                if (code!=0){
                                    layer.msg(res.msg);
                                }
                                search();
                            });
                            layer.close(index);
                        }
                    });
                    break;
                case 'editxf':
                    //给表单赋值
                    form.val("editxfInfo",{
                        id:data.id,
                        phone:data.phone,
                    })
                    layer.open({
                        type: 1,
                        offset: '50px',
                        skin: 'layui-layer-molv',
                        title: "续费",
                        area: ['800px', '400px'],
                        shade: 0,
                        shadeClose: false,
                        content: jQuery("#editxf"),
                        btn: ['确定', '取消'],
                        yes: function (index) {
                            var id = $.trim($("#id").val());//Id
                            var ygtc = $.trim($("#ygtc").val());//已购套餐
                            var xfyf = $("#xfyf").val();//续费月份
                            var params = {
                                id: id,
                                ygtc: ygtc,
                                xfyf: xfyf
                            }
                            CoreUtil.sendPut("/tSeats/updateXf", params, function (res) {
                                var code = res.code;
                                //同步数据失败
                                if (code!=0){
                                    layer.msg(res.msg);
                                }
                                search();
                            });
                            layer.close(index);
                        }
                    });
                    break;
            }
        });

        //导出
        $('#export').on('click', function () {
            //原先分页limit
            var exportParams = {
                limit: 10000,
                account: $("#accountidSc").val(),
                roleId: $("#roleIdSC").val(),
                smfs: $("#smfs").val(),
                state: $("#stateSC").val(),
                corporatename: $("#corporatenameSC").val(),
                salesname: $("#salesnameSC").val()
            };
            CoreUtil.sendPost("/tSeats/listByPage", exportParams, function (res) {
                //初始化渲染数据
                if (res.data != null && res.data.records != null) {
                    table.exportFile(tableIns1.config.id, res.data.records, 'xls');
                }
            });
        });

        //删除
        var tipDialog=function (ids) {
            layer.open({
                content: "确定要删除么?",
                yes: function(index, layero){
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                    CoreUtil.sendDelete("/tSeats/delete",ids,function (res) {
                        layer.msg(res.msg, {time:1000},function () {
                            search();
                        });
                    });
                }
            });
        };

        //返回
        $("#btn_cancel").click(function() {
            $(".table_div").show();
            $(".operation").hide();
            return false;
        });
        //返回
        $("#btn_cancelzjl").click(function() {
            $(".table_div").show();
            $(".operation").hide();
            return false;
        });
        //监听保存
        form.on('submit(submit)', function(data){
            if(data.field.id===undefined || data.field.id===null || data.field.id===""){
                CoreUtil.sendPost("/tSeats/add",data.field,function (res) {
                    if(res.code == "0"){
                        $(".table_div").show();
                        $(".operation").hide();
                        search();
                    }else {
                        layui.msg(res.msg);
                    }
                });
            }else {
                CoreUtil.sendPut("/tSeats/update",data.field,function (res) {
                    $(".table_div").show();
                    $(".operation").hide();
                    search();
                });
            }
            return false;
        });
        //监听保存总经理级别
        form.on('submit(submitzjl)', function(data){
            if(data.field.id===undefined || data.field.id===null || data.field.id===""){
                CoreUtil.sendPost("/tSeats/add",data.field,function (res) {
                    if(res.code == "0"){
                        $(".table_div").show();
                        $(".operation").hide();
                        search();
                    }else {
                        layui.msg(res.msg);
                    }
                });
            }else {
                CoreUtil.sendPut("/tSeats/update",data.field,function (res) {
                    $(".table_div").show();
                    $(".operation").hide();
                    search();
                });
            }
            return false;
        });
    });
    //加载表格
    function tableIns(){
        //根据部门区分表格
        var deptName = userInfo.sysRoleName;
        if (!tableIns1 && (deptName.indexOf("管理员")>-1 || deptName.indexOf("代理")>-1)) {
            //加载table
            tableIns1 = table.render({
                elem: '#showTable'
                , contentType: 'application/json'
                , headers: {"authorization": token}
                , page: true //开启分页
                , url: '/tSeats/listByPage' //数据接口
                , method: 'POST'
                , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": CoreUtil.isEmpty(res.data) ? 0 : res.data.total, //解析数据长度
                        "data": CoreUtil.isEmpty(res.data) ? null : res.data.records //解析数据列表
                    }
                }
                , cols: [
                    [
                        {type: 'checkbox', fixed: 'left'},
                        {title: "序号",type: "numbers", width: 130, fixed: "left"},
                        {field: 'accountid', title: '账号', sort: true,align:"center",  width: 130, fixed: "left"},
                        {field: 'corporatename', title: '公司名称', sort: true,align:"center",  width: 130, fixed: "left"},
                        {field: 'contacts', title: '联系人', sort: true,align:"center",  width: 130},
                        {field: 'phone', title: '联系方式', sort: true,align:"center",  width: 130},
                        {field: 'role', title: '角色', templet: function (item) {
                                for (const role in userRoles) {
                                    if(role.id==item) return role.name;
                                }
                            },sort: true,align:"center",  width: 130},
                        {field: 'state', title: '状态', templet: function (item) {
                                if (item.state === '0') {
                                    return '  <input type="checkbox" lay-skin="switch" lay-text="启用|禁用" checked disabled>';
                                }
                                if (item.state === '1') {
                                    return '  <input type="checkbox" lay-skin="switch" lay-text="启用|禁用" disabled>';
                                }
                            }, sort: true,align:"center",  width: 130
                        },
                        {
                            field: 'tcType', title: '套餐类型', templet: function (item) {

                                if (item.state === '0') {
                                    return '坐席账户';
                                }
                                if (item.state === '1') {
                                    return '套餐账户';
                                }
                            }, sort: true,align:"center",  width: 130
                        },
                        {field: 'residue', title: '剩余分钟数', sort: true,align:"center",  width: 130},
                        {field: 'amount', title: '当前分钟金额（元）', sort: true,align:"center",  width: 130},
                        {field: 'createtime', title: '创建时间', sort: true,align:"center",  width: 130},
                        {field: 'endtime', title: '到期时间', sort: true,align:"center",  width: 130},
                        {field: 'tccztime', title: '套餐重置时间', sort: true,align:"center",  width: 130},
                        {field: 'line', title: '线路', sort: true,align:"center",  width: 130},
                        {field: 'seats', title: '坐席数量', sort: true,align:"center",  width: 130},
                        {field: 'mode', title: '模式', sort: true,align:"center",  width: 130},
                        {field: 'salesname', title: '销售姓名', sort: true,align:"center",  width: 130},
                        {width: 280, toolbar: "#tool", title: '操作', fixed: "right"}
                    ]
                ]
                , toolbar: '#toolbar'
            });
        } else {
            //加载table
            tableIns1 = table.render({
                elem: '#showTable'
                , contentType: 'application/json'
                , headers: {"authorization": token}
                , page: true //开启分页
                , url: '/tSeats/listByPage' //数据接口
                , method: 'POST'
                , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": CoreUtil.isEmpty(res.data) ? 0 : res.data.total, //解析数据长度
                        "data": CoreUtil.isEmpty(res.data) ? null : res.data.records //解析数据列表
                    }
                }
                , cols: [
                    [
                        {type: 'checkbox', fixed: 'left'},
                        {title: "序号",type: "numbers", width: 130, fixed: "left"},
                        {field: 'accountid', title: '账号', sort: true,align:"center",  width: 130, fixed: "left"},
                        {
                            field: 'state', title: '状态', templet: function (item) {
                                if (item.state === '0') {
                                    return '  <input type="checkbox" lay-skin="switch" lay-text="启用|禁用" checked disabled>';
                                }
                                if (item.state === '1') {
                                    return '  <input type="checkbox" lay-skin="switch" lay-text="启用|禁用" disabled>';
                                }
                            }, sort: true,align:"center",  width: 130
                        },
                        {field: 'contacts', title: '姓名', sort: true,align:"center",  width: 130, fixed: "left"},
                        {field: 'phone', title: '主叫号码', sort: true,align:"center",  width: 130},
                        {field: 'corporatename', title: '公司名称', sort: true,align:"center",  width: 130, fixed: "left"},
                        {field: 'dept', title: '部门', templet: function (item) {
                                for (const dept in userDepts) {
                                    if(dept.id==item) return dept.name;
                                }
                            },sort: true,align:"center",  width: 130},
                        {field: 'role', title: '角色', templet: function (item) {
                                for (const role in userRoles) {
                                    if(role.id==item) return role.name;
                                }
                            },sort: true,align:"center",  width: 130},
                        {field: 'createtime', title: '创建时间', sort: true,align:"center",  width: 130},
                        {width: 280, toolbar: "#tool", title: '操作', fixed: "right"}
                    ]
                ]
                , toolbar: '#toolbar'
            });
        }
    }

    /*layui调用*/
    layui.use(['layer', 'form'], function () {
        $ = layui.jquery;
        var form = layui.form, layer = layui.layer;

        //自定义验证规则
        form.verify({
            // fzs: [/^1[3|4|5|7|8]\d{9}$/, '手机必须11位，只能是数字。']
        });

    });

    var wait = 60;
    function time(o) {//60秒倒计时
        if (wait == 0) {
            o.removeAttribute("disabled");
            o.value = "获取验证码";
            wait = 60;
        } else {
            o.setAttribute("disabled", true);
            o.value = "重新发送(" + wait + ")";
            wait--;
            setTimeout(function () {
                time(o);
            }, 1000);
        }
    }
    //验证码
    $("#fzs").change(function () {
        var fzs = $.trim($("#fzs").val());
        var mobile = $("#mobile").val();
        if (fzs.length > 0) {
            $("#smscode").attr("disabled", false).css({"background-color": "#fff"});
            $("#btnSendCode").attr("disabled", false).removeClass("layui-btn layui-btn-primary").addClass("layui-btn layui-btn-normal");
            document.getElementById("btnSendCode").onclick = function () {
                if (wait != 60) {
                    console.log("请" + wait + "秒后再试！");
                    return;
                }
                if (fzs == '') {
                    console.log("请填写分钟数");
                    return;
                }
                $("#smscode").val("");
                time(this);

                CoreUtil.sendGet("/smscode/"+ $("#mobile").val(), null, function (res) {
                    if(res.code == 0){
                        $("#smscode").val(res.data);
                    }else{
                        layui.msg("验证码发送失败！");
                    }
                });
            }
        } else {
            $("#smscode").attr("disabled", true);
            $("#btnSendCode").attr("disabled", false).removeClass("layui-btn layui-btn-primary").addClass("layui-btn layui-btn-normal");
        }
    });

    function info(){
        CoreUtil.sendGet("/sys/home/", null, function (res) {
            userInfo = res.data.userInfo;
            userRoles = res.data.sysRole;
            userDepts = res.data.dept;
            if(userInfo.deptName=="管理员"){
                $("#roleIdSCid").show();
                $("#smfsid").show();
                $("#stateSCid").show();
                $("#lineSCid").show();
                $("#corporatenameSCid").show();
                $("#salesnameSCid").show();
            }else if(userInfo.deptName=="代理商"){
                $("#zxlxSCid").show();
                $("#stateSCid").show();
                $("#tclxSCid").show();
                $("#corporatenameSCid").show();
            }
            var belongstoId=$("#roleId");
            $.each(userRoles,function(index,item){
                belongstoId.append("<option value="+item.id+">"+item.name+"</option>");
            });
            var roleIdSC=$("#roleIdSC");
            $.each(userRoles,function(index,item){
                roleIdSC.append("<option value="+item.id+">"+item.name+"</option>");
            });
            //部门下拉选
            var deptId=$("#deptId");
            $.each(userDepts,function(index,item){
                deptId.append("<option value="+item.id+">"+item.name+"</option>");
            });
            form.render("select");
            //加载表格
            tableIns();
        });
        CoreUtil.sendGet("/tSeats/infoData/", null, function (res) {
            var code = res.code;
            var data = res.data;
            var data = res.data;
            if (code == 0) {
                var belongstoId=$("#smfs");
                $.each(data.smfss,function(index,item){
                    belongstoId.append("<option value="+item.id+">"+item.label+"</option>");
                });
                var lineSC=$("#lineSC");
                $.each(data.lines,function(index,item){
                    lineSC.append("<option value="+item.id+">"+item.label+"</option>");
                });
                var corporatenameSC=$("#corporatenameSC");
                $.each(data.corporatenames,function(index,item){
                    if (!!item){
                        corporatenameSC.append("<option value="+item+">"+item+"</option>");
                    }
                });
                var salesnameSC=$("#salesnameSC");
                $.each(data.salesnames,function(index,item){
                    if(!!item){
                        salesnameSC.append("<option value="+item+">"+item+"</option>");
                    }
                });
                form.render("select");
            }
        });
        // search();
    }

//执行查询
    function search() {
        //这里以搜索为例
        tableIns1.reload({
            where: { //设定异步数据接口的额外参数，任意设
                account: $("#accountidSc").val(),
                roleId: $("#roleIdSC").val(),
                smfs: $("#smfs").val(),
                state: $("#stateSC").val(),
                corporatename: $("#corporatenameSC").val(),
                salesname: $("#salesnameSC").val(),
                tclx: $("#tclxSC").val(),
                zxlx: $("#zxlxSC").val(),

            }
            , page: {
                curr: 1 //重新从第 1 页开始
            }
        });
    };



// })